<template>
  <div class="salary-analysis">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
        </div>
      </template>
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="城市">
          <el-select v-model="filterForm.city" placeholder="请选择城市" clearable>
            <el-option label="北京" value="北京" />
            <el-option label="上海" value="上海" />
            <el-option label="广州" value="广州" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验要求">
          <el-select v-model="filterForm.experience" placeholder="请选择经验要求" clearable>
            <el-option label="1-3年" value="1-3年" />
            <el-option label="3-5年" value="3-5年" />
            <el-option label="5-10年" value="5-10年" />
            <el-option label="10年以上" value="10年以上" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求">
          <el-select v-model="filterForm.education" placeholder="请选择学历要求" clearable>
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">应用筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 薪资分布 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>薪资分布柱状图</span>
            </div>
          </template>
          <div ref="salaryBarChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>薪资箱线图</span>
            </div>
          </template>
          <div ref="salaryBoxChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 智能感知 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>智能感知</span>
          <el-button
            type="primary"
            :loading="adviceLoading"
            :disabled="adviceLoading"
            @click="fetchAdvice"
            class="advice-btn"
          >
            <el-icon v-if="!adviceLoading" style="margin-right:4px;"><Lightning /></el-icon>
            {{ adviceLoading ? '生成中...' : '获取智能建议' }}
          </el-button>
          <span v-if="adviceLoading" class="advice-tip">智能建议生成可能需要几秒钟，请耐心等待...</span>
        </div>
      </template>
      <div v-loading="adviceLoading" class="advice-content">
        <div v-if="overallAdvice" class="overall-advice" v-html="overallAdvice"></div>
        <div v-for="(point, index) in advicePoints" :key="index" class="advice-point">
          <h3 v-html="point.title"></h3>
          <div v-html="point.content" class="advice-text"></div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Lightning } from '@element-plus/icons-vue'

// 筛选表单
const filterForm = ref({
  city: '',
  experience: '',
  education: ''
})

// 图表实例
let salaryBarChartInstance = null
let salaryBoxChartInstance = null

// 图表DOM引用
const salaryBarChart = ref(null)
const salaryBoxChart = ref(null)

// 智能感知相关
const adviceLoading = ref(false)
const overallAdvice = ref('')
const advicePoints = ref([])

// 获取薪资分布数据
const fetchSalaryDistribution = async () => {
  try {
    const params = new URLSearchParams()
    if (filterForm.value.city) {
      params.append('city', filterForm.value.city)
    }
    if (filterForm.value.experience) {
      params.append('experience', filterForm.value.experience)
    }
    if (filterForm.value.education) {
      params.append('education', filterForm.value.education)
    }

    const response = await axios.get(`http://localhost:8081/api/salary/distribution?${params.toString()}`)
    if (response.data.code === 200) {
      initSalaryBarChart(response.data.data)
      initSalaryBoxChart(response.data.data)
    }
  } catch (error) {
    ElMessage.error('获取薪资分布数据失败')
  }
}

// 初始化薪资分布柱状图
const initSalaryBarChart = (data) => {
  if (!salaryBarChart.value) return

  salaryBarChartInstance = echarts.init(salaryBarChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        return `${params[0].name}<br/>职位数量: ${params[0].value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.range),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '职位数量'
    },
    series: [
      {
        name: '职位数量',
        type: 'bar',
        data: data.map(item => item.count),
        label: {
          show: true,
          position: 'top'
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  salaryBarChartInstance.setOption(option)
}

// 初始化薪资箱线图
const initSalaryBoxChart = (data) => {
  if (!salaryBoxChart.value) return

  salaryBoxChartInstance = echarts.init(salaryBoxChart.value)
  
  // 计算每个薪资区间的统计数据
  const boxData = data.map(item => {
    const range = item.range
    let min, q1, median, q3, max
    
    if (range === '10k以下') {
      min = 0
      q1 = 5
      median = 7.5
      q3 = 10
      max = 10
    } else if (range === '10k-20k') {
      min = 10
      q1 = 12.5
      median = 15
      q3 = 17.5
      max = 20
    } else if (range === '20k-30k') {
      min = 20
      q1 = 22.5
      median = 25
      q3 = 27.5
      max = 30
    } else if (range === '30k-50k') {
      min = 30
      q1 = 35
      median = 40
      q3 = 45
      max = 50
    } else if (range === '50k以上') {
      min = 50
      q1 = 60
      median = 70
      q3 = 80
      max = 100
    }

    return [min, q1, median, q3, max]
  })

  const option = {
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const range = data[params.dataIndex].range
        const count = data[params.dataIndex].count
        return `${range}<br/>职位数量: ${count}<br/>最小值: ${params.data[0]}k<br/>下四分位数: ${params.data[1]}k<br/>中位数: ${params.data[2]}k<br/>上四分位数: ${params.data[3]}k<br/>最大值: ${params.data[4]}k`
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.range),
      boundaryGap: true,
      nameGap: 30,
      splitArea: {
        show: false
      },
      axisLabel: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '薪资 (k)',
      splitArea: {
        show: true
      }
    },
    series: [
      {
        name: '薪资分布',
        type: 'boxplot',
        datasetIndex: 0,
        data: boxData,
        itemStyle: {
          color: '#91cc75',
          borderColor: '#5470c6'
        }
      }
    ]
  }
  salaryBoxChartInstance.setOption(option)
}

// 处理筛选
const handleFilter = () => {
  fetchSalaryDistribution()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    city: '',
    experience: '',
    education: ''
  }
  handleFilter()
}

// 处理窗口大小变化
const handleResize = () => {
  salaryBarChartInstance?.resize()
  salaryBoxChartInstance?.resize()
}

// 获取智能建议
const fetchAdvice = async () => {
  try {
    adviceLoading.value = true
    const response = await axios.get('http://localhost:8081/api/advice/salary')
    if (response.data.code === 200) {
      overallAdvice.value = response.data.data.overallAdvice
      advicePoints.value = response.data.data.advicePoints
    }
  } catch (error) {
    ElMessage.error('获取智能建议失败')
  } finally {
    adviceLoading.value = false
  }
}

onMounted(() => {
  fetchSalaryDistribution()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  salaryBarChartInstance?.dispose()
  salaryBoxChartInstance?.dispose()
})
</script>

<style scoped>
.salary-analysis {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select) {
  width: 180px;
}

:deep(.el-form-item__content) {
  flex-wrap: wrap;
}

.advice-content {
  padding: 20px;
}

.overall-advice {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  line-height: 1.8;
}

.advice-point {
  margin-bottom: 30px;
}

.advice-point:last-child {
  margin-bottom: 0;
}

.advice-point h3 {
  margin-bottom: 15px;
  color: #409EFF;
}

.advice-text {
  line-height: 1.8;
  color: #606266;
}

.advice-text :deep(p) {
  margin-bottom: 10px;
}

.advice-text :deep(ul) {
  padding-left: 20px;
  margin-bottom: 10px;
}

.advice-text :deep(li) {
  margin-bottom: 5px;
}

.advice-text :deep(strong) {
  color: #303133;
}

.advice-text :deep(h3) {
  color: #409EFF;
  margin: 20px 0 10px;
}

.advice-text :deep(hr) {
  margin: 20px 0;
  border: none;
  border-top: 1px solid #ebeef5;
}

.advice-btn {
  border-radius: 24px;
  font-weight: 600;
  background: linear-gradient(90deg, #409EFF 0%, #36D1DC 100%);
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  transition: all 0.2s;
  padding: 0 24px;
}
.advice-btn:hover {
  filter: brightness(1.08);
  box-shadow: 0 4px 16px rgba(64,158,255,0.15);
}
.advice-tip {
  margin-left: 16px;
  color: #909399;
  font-size: 14px;
  vertical-align: middle;
}
</style> 